import React, { useState, useImperativeHandle, forwardRef, useEffect } from 'react';
import { Button, Space, Modal, Form, Input, Table, message, Select, Badge } from 'antd';
import request from '@/utils/request';
import { useNavigate } from 'react-router-dom';

const TopActionBar = forwardRef(({ onConvertSuccess, showReleaseHistory = true, onManualArchive }, ref) => {
  const [convertModalVisible, setConvertModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);
  const [downloadingCount, setDownloadingCount] = useState(0);
  const navigate = useNavigate();

  // 获取执行中的订单数（供外部调用）
  const fetchDownloadingOrderCount = async () => {
    try {
      const response = await request.get('/Management/DownloadingOrderCount');
      if (response.status === 200 && response.data?.code === 200) {
        setDownloadingCount(response.data.data?.downloading_count || 0);
      }
    } catch (e) {
      // 静默处理
    }
  };

  useImperativeHandle(ref, () => ({
    refreshDownloadingCount: fetchDownloadingOrderCount
  }));

  // 可选：挂载时拉一次，避免为空
  useEffect(() => {
    fetchDownloadingOrderCount();
  }, []);

  const handleConvert = async () => {
    try {
      setLoading(true);
      setResult(null);
      const values = await form.validateFields();
      const res = await request.post('/Management/DataConvert', values);
      if (res.status === 200 && res.data.code === 200) {
        setResult(res.data.data);
        message.success('转换成功');
        if (onConvertSuccess) {
          onConvertSuccess();
        }
      } else {
        message.error(res.data.msg || '转换失败');
      }
    } catch (e) {
      if (e.errorFields) return;
      message.error(e?.message || '转换失败');
    } finally {
      setLoading(false);
    }
  };

  const handleOpen = () => {
    setConvertModalVisible(true);
    setResult(null);
    form.setFieldsValue({
      file_type: 1,
      endswith_format: 'csv',
      file_path: '',
      out_path: ''
    });
  };

  const handleClose = () => {
    setConvertModalVisible(false);
    setResult(null);
    form.resetFields();
  };

  const columns = [
    {
      title: 'xml file',
      dataIndex: 'file_xml',
      key: 'file_xml',
    },
    {
      title: 'data file',
      dataIndex: 'file_data',
      key: 'file_data',
    },
  ];

  return (
    <>
      <Space>
        {onManualArchive && (
          <Button type="primary" onClick={onManualArchive}>
            手动归档
          </Button>
        )}
        <Button type="primary" onClick={handleOpen}>
          数据转换
        </Button>
        <Badge count={downloadingCount} size="small">
          <Button type="primary" onClick={() => navigate('/download-order')}>
            下载订单
          </Button>
        </Badge>
        <Button type="primary" onClick={() => navigate('/my-favorites')}>
          我的收藏
        </Button>
        {showReleaseHistory && (
          <Button type="primary" onClick={() => navigate('/release-history')}>
            发布历史
          </Button>
        )}
      </Space>
      <Modal
        title="数据转换"
        open={convertModalVisible}
        onCancel={handleClose}
        footer={null}
        width={result ? '80vw' : 500}
        destroyOnHidden
      >
        {result ? (
          <div style={{ minHeight: 400, maxHeight: 'calc(60vh + 100px)', overflow: 'auto' }}>
            <Table
              columns={columns}
              dataSource={result}
              rowKey={(row, idx) => idx}
              pagination={false}
              bordered
              size="small"
              scroll={{ x: 'max-content', y: '60vh' }}
            />
          </div>
        ) : (
          <Form form={form} layout="vertical">
            <Form.Item
              label="转换类型"
              name="file_type"
              rules={[{ required: true, message: '请选择转换类型' }]}
              initialValue={1}
            >
              <Select placeholder="请选择转换类型" onChange={v => {
                form.setFieldsValue({ endswith_format: v === 1 ? 'csv' : 'jpg' });
              }}>
                <Select.Option value={1}>表格</Select.Option>
                <Select.Option value={2}>图像</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item noStyle shouldUpdate={(prev, curr) => prev.file_type !== curr.file_type}>
              {() => (
                <Form.Item
                  label="目标格式"
                  name="endswith_format"
                  rules={[{ required: true, message: '请选择目标格式' }]}
                  initialValue="csv"
                >
                  <Select placeholder="请选择目标格式">
                    {form.getFieldValue('file_type') === 1 ? (
                      <>
                        <Select.Option value="csv">csv</Select.Option>
                        <Select.Option value="xlsx">xlsx</Select.Option>
                      </>
                    ) : (
                      <>
                        <Select.Option value="jpg">jpg</Select.Option>
                        <Select.Option value="png">png</Select.Option>
                        <Select.Option value="bmp">bmp</Select.Option>
                      </>
                    )}
                  </Select>
                </Form.Item>
              )}
            </Form.Item>
            <Form.Item
              label="文件路径"
              name="file_path"
              rules={[{ required: true, message: '请输入文件路径' }]}
            >
              <Input placeholder="请输入文件路径" />
            </Form.Item>
            <Form.Item
              label="目标路径"
              name="out_path"
              rules={[{ required: true, message: '请输入目标路径' }]}
            >
              <Input placeholder="请输入目标路径" />
            </Form.Item>
            <div>
              <Space>
                <Button onClick={handleClose}>取消</Button>
                <Button type="primary" loading={loading} onClick={handleConvert}>
                  确认
                </Button>
              </Space>
            </div>
          </Form>
        )}
      </Modal>
    </>
  );
});

export default TopActionBar;